﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using DoVuiKinhThanh.Domain;
using MessageBox = System.Windows.MessageBox;

namespace DoVuiKinhThanh
{
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Collections.ObjectModel;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const string PROJECT_FILE_FILTER = "DVKT project files (.dvkt)|*.dvkt";

        private SlideShow m_slideShow;

        private string PROJECT_FILE_EXTENSION = ".dvkt";

        #region IConstructors

        public MainWindow()
        {
            InitializeComponent();
            AllQuizes = new ObservableCollection<Quiz>();
        }

        #endregion

        #region IMethods

        private Quiz CreateOrEditQuiz(Quiz selectedQuiz)
        {
            if (AllQuizes == null)
            {
                return null;
            }
            var dlgQuiz = selectedQuiz != null ? new QuizEditing(selectedQuiz.Clone()) : new QuizEditing();
            var dialogResult = dlgQuiz.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                var pos = -1;
                if (selectedQuiz != null)
                {
                    pos = AllQuizes.IndexOf(selectedQuiz);
                    AllQuizes.Remove(selectedQuiz);
                }
                pos = (pos < 0) ? AllQuizes.Count : pos;
                AllQuizes.Insert(pos, dlgQuiz.EditingQuiz);
                return dlgQuiz.EditingQuiz;
            }
            return null;
        }

        private void OnBtnAddToSelectionClicked(object sender, RoutedEventArgs e)
        {
            var selectedQuizesInAllQuizes = new List<Quiz>(m_lstQuizes.SelectedItems.Cast<Quiz>());
            SetSelectedQuizes(selectedQuizesInAllQuizes, true);
            BindData();
        }

        private void SetSelectedQuizes(List<Quiz> selectedQuizesInAllQuizes, bool isSelected)
        {
            foreach (var quiz in selectedQuizesInAllQuizes)
            {
                quiz.Selected = isSelected;
            }
        }

        private void OnBtnCreateQuizClicked(object sender, RoutedEventArgs e)
        {
            CreateOrEditQuiz(null);
            BindData();
        }

        private void OnBtnDeleteQuizClicked(object sender, RoutedEventArgs e)
        {
            if (AllQuizes == null || SelectedQuiz == null || !AllQuizes.Contains(SelectedQuiz))
            {
                return;
            }
            var msg = string.Format("Bạn muốn xóa câu đố: {0}", SelectedQuiz.ContentWithoutFormat);
            if (MessageBox.Show(msg, "Thông báo", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                AllQuizes.Remove(SelectedQuiz);
                BindData();
            }
        }

        private void OnBtnEditQuizClicked(object sender, RoutedEventArgs e)
        {
            SelectedQuiz = CreateOrEditQuiz(SelectedQuiz);
            BindData();
        }

        private void OnBtnExitClicked(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void OnBtnRemoveFromSelectionClicked(object sender, RoutedEventArgs e)
        {
            var selectedQuizes = new List<Quiz>(m_lstPlayingQuizes.SelectedItems.Cast<Quiz>());
            SetSelectedQuizes(selectedQuizes, false);
            BindData();
        }

        private void OnBtnShowQuizClicked(object sender, RoutedEventArgs e)
        {
            if (m_slideShow == null || !m_slideShow.IsVisible)
            {
                m_slideShow = new SlideShow(PlayingQuizes);
                m_slideShow.Loaded += OnSlideShowLoaded;
                m_slideShow.Closed += OnSlideShowClosed;
                m_slideShow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                m_slideShow.WindowState = WindowState.Normal;
                m_slideShow.WindowStyle = WindowStyle.ThreeDBorderWindow;

                //var currentScreen = Screen.FromRectangle(new System.Drawing.Rectangle((int) Left, (int) Top, (int) Width, (int) Height));
                //var screen = Screen.AllScreens.FirstOrDefault(s => s != currentScreen);
                var screen = Screen.AllScreens.FirstOrDefault(s => !s.Primary);
                if (screen != null)
                {
                    var area = screen.WorkingArea;
                    if (!area.IsEmpty)
                    {
                        m_slideShow.WindowStartupLocation = WindowStartupLocation.Manual;
                        m_slideShow.Left = area.Left;
                        m_slideShow.Top = area.Top;
                        m_slideShow.Width = area.Width;
                        m_slideShow.Height = area.Height;
                        m_slideShow.WindowStyle = WindowStyle.None;
                        m_slideShow.Topmost = true;
                    }
                }
                m_slideShow.StartShow(screen != null);
            }
            else if (m_slideShow != null)
            {
                m_slideShow.Close();
                m_slideShow.Loaded -= OnSlideShowLoaded;
                m_slideShow.Closed -= OnSlideShowClosed;
                m_slideShow = null;
            }
        }

        public void OnSlideShowLoaded(object sender, RoutedEventArgs e)
        {
            if (m_slideShow.IsVisible)
            {
                m_btnShowQuiz.Content = "Dừng chơi";
            }
        }

        public void OnSlideShowClosed(object sender, System.EventArgs e)
        {
            m_btnShowQuiz.Content = "Bắt đầu chơi";
        }

        private void OnQuizSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = sender as System.Windows.Controls.ListBox;
            if (listBox != null)
            {
                SelectedQuiz = null;
                SelectedQuiz = listBox.SelectedItem as Quiz;
            }
            m_ctrlSelectedQuiz.BindQuizData(SelectedQuiz);
        }

        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            m_lstQuizes.ItemsSource = NotPlayingQuizes;
            m_lstPlayingQuizes.ItemsSource = PlayingQuizes;
        }

        #endregion

        #region IProperties

        public Quiz SelectedQuiz
        {
            get;
            set;
        }

        public ObservableCollection<Quiz> AllQuizes
        {
            get;
            set;
        }

        public ObservableCollection<Quiz> NotPlayingQuizes
        {
            get
            {
                return new ObservableCollection<Quiz>(AllQuizes.Where(q => !q.Selected).ToList());
            }
        }

        public ObservableCollection<Quiz> PlayingQuizes
        {
            get
            {
                return new ObservableCollection<Quiz>(AllQuizes.Where(q => q.Selected).ToList());
            }
        }

        #endregion

        private void OnBtnSaveQuizesClicked(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.DefaultExt = PROJECT_FILE_EXTENSION; // Default file extension 
            saveFileDialog.Filter = PROJECT_FILE_FILTER; // Filter files by extension 
            var dialogResult = saveFileDialog.ShowDialog(this);
            if (dialogResult.HasValue && dialogResult.Value)
            {
                using (TextWriter textWriter = new StreamWriter(saveFileDialog.FileName))
                {
                    Project project = new Project { Quizes = AllQuizes };
                    XmlSerializer serializer = new XmlSerializer(typeof(Project));
                    serializer.Serialize(textWriter, project);
                }
            }
        }

        private void OnBtnLoadQuizesClicked(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.CheckPathExists = true;
            openFileDialog.DefaultExt = PROJECT_FILE_EXTENSION; // Default file extension 
            openFileDialog.Filter = PROJECT_FILE_FILTER; // Filter files by extension 
            var dialogResult = openFileDialog.ShowDialog(this);
            if (dialogResult.HasValue && dialogResult.Value)
            {
                using (TextReader textReader = new StreamReader(openFileDialog.FileName))
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(Project));
                    Project project = deserializer.Deserialize(textReader) as Project;
                    AllQuizes = project.Quizes;
                    BindData();
                }
            }
        }

        private void OnBtnExportQuizClicked(object sender, RoutedEventArgs e)
        {
            PowerpointHelper.CreatePowerPointPresentation(PlayingQuizes);
        }
    }
}